package com.shopping.interceptor;

import com.shopping.bean.User;
import com.shopping.util.LayData;
import com.shopping.util.SYS;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSON;

public class ShoppingLoginINterceptor implements HandlerInterceptor {
    //在Handler处理之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if (obj != null) {
            User user = (User) obj;
            System.out.println("进入拦截器时，会话中的用户 userid: " + user.getUserid());
        } else {
            System.out.println("进入拦截器时，会话中用户信息为空");
        }
        //判断是否存在登录数据
        if (obj != null) {
            return true;
        } else {
            String requestwith = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(requestwith)) {
                //ajax
                LayData result = LayData.success(401, "您还没有登录,请登录");
                String json = JSON.toJSONString(result);
                response.setHeader("Content-Type", "application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);


            } else {
                //重定向
                String path = request.getContextPath();
                String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
                response.sendRedirect(basePath + "page/login");
            }
                return false;
            }
        }

//在Handler处理之后立即执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        Object obj = session.getAttribute(SYS.SHOPPING_LOGIN_USER);
        if (obj != null) {
            User user = (User) obj;
            System.out.println("离开拦截器时，会话中的用户 userid: " + user.getUserid());
        } else {
            System.out.println("离开拦截器时，会话中用户信息为空");
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
//一个请求结束spring框架访问后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
